package com.huan.springcloud.config;

import com.huan.springcloud.product.ProductApiConfig;
import com.huan.springcloud.user.UserApiConfig;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;

/**
 * 为客户端注册
 *
 * @author huan.fu
 * @date 2023/8/15 - 10:09
 */
@Component
public class ClientSpecificationRegister implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        registerClientConfiguration(registry, "product", ProductApiConfig.class);
        registerClientConfiguration(registry, "user", UserApiConfig.class);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // ignore
    }

    private static void registerClientConfiguration(BeanDefinitionRegistry registry, Object name,
                                                    Object configuration) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder
                .genericBeanDefinition(ClientSpecification.class);
        builder.addConstructorArgValue(name);
        builder.addConstructorArgValue(configuration);
        registry.registerBeanDefinition(name + ".ClientSpecification", builder.getBeanDefinition());
    }
}
